import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Tag, Upload, message, Input, Select, Tooltip, Popconfirm, Progress } from 'antd';
import { 
  UploadOutlined, 
  FileOutlined, 
  FilePdfOutlined, 
  FileWordOutlined, 
  FileExcelOutlined, 
  FilePptOutlined, 
  FileImageOutlined, 
  FileTextOutlined, 
  EyeOutlined, 
  DeleteOutlined 
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { useParams } from 'react-router-dom';
import { RootState } from '../../store';
import { fetchDocumentsByKnowledgeBaseId, uploadDocument } from '../../store/slices/document';
import { Document } from '../../types/document';
import PageHeader from '../common/PageHeader';

const { Search } = Input;
const { Option } = Select;

interface DocumentListProps {
  knowledgeBaseId?: number;
}

const DocumentList: React.FC<DocumentListProps> = ({ knowledgeBaseId }) => {
  const { id: urlKnowledgeBaseId } = useParams<{ id: string }>();
  const dispatch = useDispatch();
  const { documents, loading, uploadProgress } = useSelector((state: RootState) => state.document);
  const { knowledgeBases } = useSelector((state: RootState) => state.knowledgeBase);

  const [searchTerm, setSearchTerm] = useState('');
  const [fileTypeFilter, setFileTypeFilter] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<string | null>(null);
  const [filteredDocuments, setFilteredDocuments] = useState<Document[]>([]);
  const [selectedKnowledgeBaseId, setSelectedKnowledgeBaseId] = useState<number | undefined>(knowledgeBaseId);

  // 处理从URL中获取的知识库ID
  useEffect(() => {
    if (urlKnowledgeBaseId) {
      setSelectedKnowledgeBaseId(Number(urlKnowledgeBaseId));
    } else if (knowledgeBaseId) {
      setSelectedKnowledgeBaseId(knowledgeBaseId);
    }
  }, [urlKnowledgeBaseId, knowledgeBaseId]);

  // 加载文档
  useEffect(() => {
    if (selectedKnowledgeBaseId) {
      dispatch(fetchDocumentsByKnowledgeBaseId(selectedKnowledgeBaseId) as any);
    }
  }, [dispatch, selectedKnowledgeBaseId]);

  // 过滤文档
  useEffect(() => {
    let filtered = [...documents];

    if (searchTerm) {
      filtered = filtered.filter(doc => 
        doc.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        doc.fileName.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (fileTypeFilter) {
      filtered = filtered.filter(doc => doc.fileType === fileTypeFilter);
    }

    if (statusFilter) {
      filtered = filtered.filter(doc => doc.status === statusFilter);
    }

    setFilteredDocuments(filtered);
  }, [documents, searchTerm, fileTypeFilter, statusFilter]);

  // 获取文件图标
  const getFileIcon = (fileType: string) => {
    switch (fileType.toLowerCase()) {
      case 'pdf':
        return <FilePdfOutlined style={{ color: '#f5222d' }} />;
      case 'doc':
      case 'docx':
        return <FileWordOutlined style={{ color: '#1890ff' }} />;
      case 'xls':
      case 'xlsx':
        return <FileExcelOutlined style={{ color: '#52c41a' }} />;
      case 'ppt':
      case 'pptx':
        return <FilePptOutlined style={{ color: '#faad14' }} />;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return <FileImageOutlined style={{ color: '#722ed1' }} />;
      case 'txt':
        return <FileTextOutlined style={{ color: '#595959' }} />;
      default:
        return <FileOutlined />;
    }
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="default">待处理</Tag>;
      case 'PROCESSING':
        return <Tag color="processing">处理中</Tag>;
      case 'COMPLETED':
        return <Tag color="success">已完成</Tag>;
      case 'FAILED':
        return <Tag color="error">失败</Tag>;
      default:
        return <Tag color="default">{status}</Tag>;
    }
  };

  // 处理文件上传
  const handleUpload = (info: any) => {
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };

  // 自定义上传逻辑
  const customUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    
    if (!selectedKnowledgeBaseId) {
      message.error('请先选择知识库');
      onError('No knowledge base selected');
      return;
    }

    try {
      await dispatch(uploadDocument({ 
        file, 
        knowledgeBaseId: selectedKnowledgeBaseId 
      }) as any);
      onSuccess('Upload successful');
    } catch (error) {
      onError('Upload failed');
    }
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchTerm(value);
  };

  // 处理删除文档
  const handleDelete = (id: number) => {
    // 这里添加删除文档的逻辑
    console.log('删除文档:', id);
  };

  // 处理查看文档
  const handleView = (id: number) => {
    // 这里添加查看文档的逻辑
    console.log('查看文档:', id);
  };

  // 处理知识库切换
  const handleKnowledgeBaseChange = (value: number) => {
    setSelectedKnowledgeBaseId(value);
  };

  // 表格列定义
  const columns = [
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      render: (text: string, record: Document) => (
        <Space>
          {getFileIcon(record.fileType)}
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      render: (fileSize: number) => {
        const kb = fileSize / 1024;
        if (kb < 1024) {
          return `${kb.toFixed(2)} KB`;
        } else {
          return `${(kb / 1024).toFixed(2)} MB`;
        }
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string, record: Document) => {
        if (status === 'PROCESSING' && record.processingMessage) {
          return (
            <Tooltip title={record.processingMessage}>
              {getStatusTag(status)}
            </Tooltip>
          );
        }
        return getStatusTag(status);
      },
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Document) => (
        <Space size="small">
          <Tooltip title="查看">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleView(record.id)} 
              disabled={record.status !== 'COMPLETED'}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除此文档吗?"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="text" 
                danger 
                icon={<DeleteOutlined />} 
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 构建额外操作区域
  const extraContent = (
    <Space>
      <Search 
        placeholder="搜索文档" 
        onSearch={handleSearch} 
        style={{ width: 200 }} 
        allowClear
      />
      
      <Select 
        placeholder="文件类型"
        style={{ width: 120 }}
        allowClear
        onChange={(value) => setFileTypeFilter(value)}
      >
        <Option value="pdf">PDF</Option>
        <Option value="docx">Word</Option>
        <Option value="xlsx">Excel</Option>
        <Option value="pptx">PowerPoint</Option>
        <Option value="txt">文本</Option>
      </Select>
      
      <Select 
        placeholder="状态"
        style={{ width: 120 }}
        allowClear
        onChange={(value) => setStatusFilter(value)}
      >
        <Option value="PENDING">待处理</Option>
        <Option value="PROCESSING">处理中</Option>
        <Option value="COMPLETED">已完成</Option>
        <Option value="FAILED">失败</Option>
      </Select>
      
      {!knowledgeBaseId && (
        <Select
          placeholder="选择知识库"
          style={{ width: 200 }}
          value={selectedKnowledgeBaseId}
          onChange={handleKnowledgeBaseChange}
        >
          {knowledgeBases.map(kb => (
            <Option key={kb.id} value={kb.id}>{kb.name}</Option>
          ))}
        </Select>
      )}
      
      <Upload
        customRequest={customUpload}
        onChange={handleUpload}
        showUploadList={false}
        accept=".pdf,.doc,.docx,.txt,.md,.ppt,.pptx,.xls,.xlsx"
        disabled={!selectedKnowledgeBaseId}
      >
        <Button 
          type="primary" 
          icon={<UploadOutlined />}
          disabled={!selectedKnowledgeBaseId}
        >
          上传文档
        </Button>
      </Upload>
    </Space>
  );

  return (
    <div className="document-list">
      <PageHeader 
        title="文档管理" 
        extra={extraContent}
        breadcrumbs={[
          { title: '首页', path: '/' },
          { title: '文档管理' },
        ]}
      />

      {uploadProgress > 0 && uploadProgress < 100 && (
        <div style={{ marginBottom: 16 }}>
          <Progress percent={uploadProgress} status="active" />
        </div>
      )}

      <Table
        columns={columns}
        dataSource={filteredDocuments}
        rowKey="id"
        loading={loading}
        pagination={{ defaultPageSize: 10 }}
      />
    </div>
  );
};

export default DocumentList; 